package logger

import (
	cf "BackupDatabase/config"
	"github.com/natefinch/lumberjack"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"os"
)

var logger *zap.Logger

func Init() (err error) {
	writeSyncer := getLogSyncer()

	encode := getEncode()
	l := new(zapcore.Level)
	err = l.UnmarshalText([]byte(cf.Config.LogConfig.Level))
	if err != nil {
		return
	}

	var core zapcore.Core

	if cf.Config.LogConfig.Level == "debug" { // 开发模式
		core = zapcore.NewTee(
			zapcore.NewCore(encode, writeSyncer, zapcore.DebugLevel),             // 文件写
			zapcore.NewCore(encode, zapcore.Lock(os.Stdout), zapcore.DebugLevel)) // 终端写
	} else {
		core = zapcore.NewCore(encode, writeSyncer, zapcore.DebugLevel)
	}

	logger = zap.New(core, zap.AddCaller()) // zap.AddCaller() 记录调用方
	zap.ReplaceGlobals(logger)

	return
}

func getEncode() zapcore.Encoder {
	config := zapcore.EncoderConfig{
		TimeKey:        "ts",
		LevelKey:       "level",
		NameKey:        "logger",
		CallerKey:      "caller",
		FunctionKey:    zapcore.OmitKey,
		MessageKey:     "msg",
		StacktraceKey:  "stacktrace",
		LineEnding:     zapcore.DefaultLineEnding,
		EncodeLevel:    zapcore.LowercaseLevelEncoder,
		EncodeTime:     zapcore.TimeEncoderOfLayout("2006-01-02 15:04:05.000"),
		EncodeDuration: zapcore.SecondsDurationEncoder,
		EncodeCaller:   zapcore.ShortCallerEncoder,
	}
	return zapcore.NewJSONEncoder(config)
}

func getLogSyncer() zapcore.WriteSyncer {
	lumberjackLogger := &lumberjack.Logger{ // 日志切割
		Filename:   cf.Config.LogConfig.Filename,   // 文件名称
		MaxSize:    cf.Config.LogConfig.MaxSize,    // 单个文件大小 单位m
		MaxAge:     cf.Config.LogConfig.MaxAge,     // 备份数量
		MaxBackups: cf.Config.LogConfig.MaxBackups, // 最大备份天数
		Compress:   false,
	}

	return zapcore.AddSync(lumberjackLogger)
}
